/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package estg.dae.projecto.bank.controllers;

import estg.dae.projecto.bank.impl.ElectronicOperationTO;
import estg.dae.projecto.bank.model.ElectronicTransfer;
import java.util.Calendar;
import java.util.Collection;
import javax.ejb.Timer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.TimerService;

/**
 *
 * @author Marco
 */
@Stateless
public class OfflineTransferTimerBean implements OfflineTransferTimerLocal {
    private static final String TIMER_ID = "OfflineTransferTimer";

    @Resource
    TimerService timerService;
    @EJB
    private BankSessionLocal controller;

    @Timeout
    public void processOfflineTransfers(Timer timer) {
        Collection<ElectronicTransfer> transfers = controller.getOfflineTransfers();

        for(ElectronicTransfer transfer : transfers) {
            controller.sendOfflineTransfer(new ElectronicOperationTO(transfer));
        }
    }

    @PostConstruct
    public void initializeTimer() {
        timerService.createTimer(Calendar.getInstance().getTime(), 60000, TIMER_ID);
    }

    @PreDestroy
    public void finalizeTimer() {
        Collection timers = timerService.getTimers();

        for(Object object : timers) {
            Timer timer = (Timer)object;
            if (timer.getInfo().equals(TIMER_ID))
                timer.cancel();
        }
    }
}
